<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { isLoggedIn, getUserInfo, getAccessToken, logout } from '../utils/auth.js'
import { showToast } from 'vant'

const router = useRouter()
const userInfo = ref(null)
const loading = ref(false)
const editingNickname = ref(false)
const newNickname = ref('')

// 实名认证状态
const verifyStatus = ref(0) // 0-未认证, 1-审核中, 2-已认证, 3-审核驳回

onMounted(() => {
  if (!isLoggedIn()) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  loadUserInfo()
})

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true
  try {
    const token = getAccessToken()
    if (!token) {
      showToast('未找到登录凭证')
      return
    }

    const response = await fetch('http://localhost:8000/user/idcard/status', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.code === 200 && result.data) {
      // 合并本地存储和API返回的数据
      const localInfo = getUserInfo()
      userInfo.value = {
        ...localInfo,
        nickname: result.data.nickname || localInfo?.nickname || '用户',
        avatar: result.data.avatar || localInfo?.avatar,
        avatar_url: result.data.avatar || localInfo?.avatar_url,
        phone: result.data.phone || localInfo?.phone || ''
      }
      verifyStatus.value = result.data.verify_status || 0
      newNickname.value = userInfo.value.nickname || ''
    } else {
      // 使用本地存储的信息
      userInfo.value = getUserInfo()
      if (userInfo.value) {
        newNickname.value = userInfo.value.nickname || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    // 使用本地存储的信息
    userInfo.value = getUserInfo()
    if (userInfo.value) {
      newNickname.value = userInfo.value.nickname || ''
    }
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 开始编辑昵称
const startEditNickname = () => {
  editingNickname.value = true
  newNickname.value = userInfo.value?.nickname || ''
}

// 取消编辑昵称
const cancelEditNickname = () => {
  editingNickname.value = false
  newNickname.value = userInfo.value?.nickname || ''
}

// 保存昵称
const saveNickname = async () => {
  if (!newNickname.value.trim()) {
    showToast('昵称不能为空')
    return
  }

  // TODO: 调用后端API更新昵称
  // 暂时只更新本地显示
  if (userInfo.value) {
    userInfo.value.nickname = newNickname.value.trim()
    // 更新本地存储
    const localInfo = getUserInfo()
    if (localInfo) {
      localInfo.nickname = newNickname.value.trim()
      localStorage.setItem('user_info', JSON.stringify(localInfo))
    }
    showToast('昵称更新成功')
  }
  editingNickname.value = false
}

// 前往实名认证
const goToVerifyIdentity = () => {
  router.push('/verify-identity')
}

// 退出登录
const handleLogout = () => {
  logout()
  showToast('已退出登录')
  router.push('/user/login')
}

// 实名认证状态文本
const getVerifyStatusText = () => {
  switch (verifyStatus.value) {
    case 0:
      return '未实名认证'
    case 1:
      return '审核中'
    case 2:
      return '已实名认证'
    case 3:
      return '审核驳回'
    default:
      return '未知状态'
  }
}

// 实名认证状态颜色类
const getVerifyStatusClass = () => {
  switch (verifyStatus.value) {
    case 0:
      return 'unverified'
    case 1:
      return 'pending'
    case 2:
      return 'verified'
    case 3:
      return 'rejected'
    default:
      return 'unverified'
  }
}
</script>

<template>
  <div class="personal-info-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 18L9 12L15 6" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <div class="header-title">个人信息</div>
      <div class="header-placeholder"></div>
    </div>

    <!-- 用户头像区域 -->
    <div class="avatar-section">
      <div class="avatar-container">
        <img 
          v-if="userInfo?.avatar || userInfo?.avatar_url" 
          :src="userInfo.avatar || userInfo.avatar_url" 
          :alt="userInfo?.nickname" 
          class="avatar-img"
        />
        <div v-else class="avatar-placeholder">
          {{ userInfo?.nickname?.charAt(0) || 'U' }}
        </div>
      </div>
      <div class="avatar-tip">点击头像可更换</div>
    </div>

    <!-- 信息列表 -->
    <div class="info-list">
      <!-- 昵称 -->
      <div class="info-item">
        <div class="info-label">
          <span class="info-icon">👤</span>
          <span>昵称</span>
        </div>
        <div class="info-content">
          <div v-if="!editingNickname" class="info-value" @click="startEditNickname">
            <span>{{ userInfo?.nickname || '未设置' }}</span>
            <span class="edit-arrow">编辑</span>
          </div>
          <div v-else class="edit-nickname">
            <input 
              v-model="newNickname" 
              type="text" 
              class="nickname-input"
              placeholder="请输入昵称"
              maxlength="20"
            />
            <div class="edit-actions">
              <span class="edit-btn cancel" @click="cancelEditNickname">取消</span>
              <span class="edit-btn save" @click="saveNickname">保存</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 手机号 -->
      <div class="info-item">
        <div class="info-label">
          <span class="info-icon">📱</span>
          <span>手机号</span>
        </div>
        <div class="info-content">
          <div class="info-value">
            <span>{{ userInfo?.phone || '未绑定' }}</span>
          </div>
        </div>
      </div>

      <!-- 实名认证 -->
      <div class="info-item" @click="goToVerifyIdentity">
        <div class="info-label">
          <span class="info-icon">🆔</span>
          <span>实名认证</span>
        </div>
        <div class="info-content">
          <div class="info-value">
            <span :class="['verify-badge', getVerifyStatusClass()]">
              {{ getVerifyStatusText() }}
            </span>
            <span class="arrow">></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 退出登录按钮 -->
    <div class="logout-section">
      <div class="logout-btn" @click="handleLogout">
        退出登录
      </div>
    </div>
  </div>
</template>

<style scoped>
.personal-info-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 40px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.2s;
}

.back-btn:active {
  background: #f5f5f5;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-placeholder {
  width: 40px;
}

/* 头像区域 */
.avatar-section {
  background: white;
  padding: 32px 16px;
  text-align: center;
  margin-bottom: 12px;
}

.avatar-container {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 auto 12px;
  border: 3px solid #e0e0e0;
  cursor: pointer;
  transition: transform 0.2s;
}

.avatar-container:active {
  transform: scale(0.95);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  font-weight: 600;
  color: white;
}

.avatar-tip {
  font-size: 14px;
  color: #999;
}

/* 信息列表 */
.info-list {
  background: white;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item:active {
  background: #f5f5f5;
}

.info-label {
  display: flex;
  align-items: center;
  min-width: 100px;
  font-size: 15px;
  color: #333;
}

.info-icon {
  font-size: 18px;
  margin-right: 8px;
}

.info-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.info-value {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  color: #666;
}

.edit-arrow {
  font-size: 14px;
  color: #667eea;
}

.arrow {
  font-size: 16px;
  color: #999;
  margin-left: 8px;
}

/* 编辑昵称 */
.edit-nickname {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.nickname-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 15px;
  outline: none;
}

.nickname-input:focus {
  border-color: #667eea;
}

.edit-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.edit-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-btn.cancel {
  background: #f5f5f5;
  color: #666;
}

.edit-btn.cancel:active {
  background: #e0e0e0;
}

.edit-btn.save {
  background: #667eea;
  color: white;
}

.edit-btn.save:active {
  background: #5568d3;
}

/* 实名认证状态标签 */
.verify-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.verify-badge.unverified {
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.verify-badge.pending {
  background: rgba(33, 150, 243, 0.2);
  color: #2196f3;
}

.verify-badge.verified {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.verify-badge.rejected {
  background: rgba(244, 67, 54, 0.2);
  color: #f44336;
}

/* 退出登录 */
.logout-section {
  padding: 0 16px;
  margin-top: 24px;
}

.logout-btn {
  width: 100%;
  padding: 14px;
  background: white;
  color: #f44336;
  text-align: center;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.logout-btn:active {
  background: #ffebee;
}
</style>
